//
//  NGTitleBarView.swift
//  NingguoForum
//
//  Created by zhengsw on 2025/7/17.
//  Copyright © 2025 zhengsw. All rights reserved.
//

import UIKit
import SnapKit

// MARK: - Protocol
protocol NGTitleBarViewDelegate: AnyObject {
    func titleBarView(_ titleBarView: NGTitleBarView, didSelectItemAt index: Int)
}

class NGTitleBarView: UIView {
    
    // MARK: - Properties
    private var titles: [ResponseForumDetailListModel] = []
    private var selectedIndex: Int = 0
    
    weak var delegate: NGTitleBarViewDelegate?
    
    // MARK: - UI Components
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: 100, height: 44)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(NGTitleBarCell.self, forCellWithReuseIdentifier: "NGTitleBarCell")
        return collectionView
    }()
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    // MARK: - Public Methods
    func configure(titles: [ResponseForumDetailListModel], selectedIndex: Int = 0) {
        self.titles = titles
        self.selectedIndex = selectedIndex
        collectionView.reloadData()
    }
    
    func selectTab(at index: Int, animated: Bool = true) {
        guard index >= 0 && index < titles.count else { return }
        
        selectedIndex = index
        collectionView.reloadData()
        
        if animated {
            collectionView.scrollToItem(
                at: IndexPath(item: index, section: 0),
                at: .centeredHorizontally,
                animated: true
            )
        }
    }
    
    func updateSelectedIndex(_ index: Int) {
        selectedIndex = index
        collectionView.reloadData()
    }
    
    func scrollToSelectedItem(animated: Bool = true) {
        collectionView.scrollToItem(
            at: IndexPath(item: selectedIndex, section: 0),
            at: .centeredHorizontally,
            animated: animated
        )
    }
    deinit {
        
    }
}

// MARK: - UICollectionViewDataSource
extension NGTitleBarView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return titles.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NGTitleBarCell", for: indexPath) as! NGTitleBarCell
        
        let model = titles[indexPath.item]
        let isSelected = indexPath.item == selectedIndex
        cell.configure(title: model.name ?? "", isSelected: isSelected)
        
        return cell
    }
}

// MARK: - UICollectionViewDelegate
extension NGTitleBarView: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndex = indexPath.item
        collectionView.reloadData()
        delegate?.titleBarView(self, didSelectItemAt: indexPath.item)
    }
}

// MARK: - UICollectionViewDelegateFlowLayout
extension NGTitleBarView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 可以根据标题长度动态计算宽度
        let title = titles[indexPath.item].name ?? ""
        let width = calculateTitleWidth(title)
        return CGSize(width: width, height: 44)
    }
    
    private func calculateTitleWidth(_ title: String) -> CGFloat {
        let font = UIFont.systemFont(ofSize: 16)
        let attributes = [NSAttributedString.Key.font: font]
        let size = (title as NSString).size(withAttributes: attributes)
        return max(80, size.width + 20) // 最小宽度80，左右各留10点间距
    }
}
